package co.fitstart.coach.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.coach.entity.courseware.Assessment;
import co.fitstart.coach.entity.courseware.BwhRecordList;
import co.fitstart.coach.entity.courseware.Target;
import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.BasicInformationService;
import co.fitstart.coach.service.CourseService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.round.Goal;
import co.fitstart.entity.courseware.assessment.BasicData;
import co.fitstart.entity.courseware.assessment.Disease;
import co.fitstart.entity.courseware.assessment.PostureJoint;
import co.fitstart.entity.courseware.assessment.StudentAssessment;
import co.fitstart.entity.courseware.assessment.StudentHabit;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.user.basic.BodyDataTarget;
import co.fitstart.entity.user.bwh.BwhRecord;

/**
 * 基础信息
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("/rounds/{courseRoundId}/basic-information")
public class BasicInformationController {
    private static final Logger logger = LoggerFactory.getLogger(BasicInformationController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private BasicInformationService basicInformationService;
    
    /**
     * 目标编辑页
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/target", method = RequestMethod.GET)
    public ModelAndView target(@Secure Login login,
                               @PathVariable("courseRoundId") Long courseRoundId) {
        ModelAndView modelAndView = new ModelAndView("courseware/basic/edit-target");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null) {
            if(courseRound.getCoach() != coach) {
                modelAndView.setViewName("courseware/basic/target");
            }
            
            Goal goal = basicInformationService.loadGoal(courseRound);
            
            List<BodyDataTarget> targets = basicInformationService.listBodyDataTarget(courseRound);
            
            Map<Integer, BwhRecord> bwhRecords = basicInformationService.listBwhRecord(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("weeks", courseRound.getFitnessGroup().getWeeks());
            modelAndView.addObject("goal", goal);
            modelAndView.addObject("targets", CollectionUtils.constructMapValueFromList(targets, "bodyDataType.alias"));
            modelAndView.addObject("bwhRecords", bwhRecords);
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param goal
     * @param target
     * @param bwhRecordList
     * @return
     */
    @RequestMapping(value = "/edit-target", method = RequestMethod.PATCH)
    public @ResponseBody String onEditTarget(@Secure Login login,
                                             @PathVariable("courseRoundId") Long courseRoundId,
                                             Goal goal,
                                             Target target,
                                             BwhRecordList bwhRecordList) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && !courseRound.isDisabled() && courseRound.getCoach() == coach) {
                basicInformationService.editTarget(courseRound, goal, target.getBodyDataTargets(), bwhRecordList.getBwhRecords());
            }
            
            result.success().message("保存成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#onEditTarget() error", e);
            result.fail().message("保存失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * student assessment
     * @param login
     * @param courseRoundId
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/student-assessment", method = RequestMethod.GET)
    public ModelAndView studentAssessment(@Secure Login login,
                                          @PathVariable("courseRoundId") Long courseRoundId,
                                          @RequestParam(value="scheduleId", required = false) Long scheduleId,
                                          @RequestParam(value="back", required = false) String back) {
//        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/coach-evaluation");
        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/student-assessment");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null) {
            StudentAssessment studentAssessment = basicInformationService.loadStudentAssessment(courseRound);
            
//            BasicData basicData = basicInformationService.loadBasicData(courseRound);
//            StudentHabit habit = basicInformationService.loadStudentHabit(courseRound);
//            PostureJoint postureJoint = basicInformationService.loadPostureJoint(courseRound);
            if(studentAssessment == null) {
                BasicData basicData = basicInformationService.loadBasicData(courseRound);
                PostureJoint postureJoint = basicInformationService.loadPostureJoint(courseRound);
                
                Assessment assessment = new Assessment(basicData, postureJoint);
                
                modelAndView.addObject("studentAssessment", assessment);
            } else {
                modelAndView.addObject("studentAssessment", studentAssessment);
            }
            
            modelAndView.addObject("courseRound", courseRound);
//            modelAndView.addObject("basicData", basicData);
//            modelAndView.addObject("habit", habit);
//            modelAndView.addObject("postureJoint", postureJoint);
            modelAndView.addObject("edit", courseRound.getCoach() == coach);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param basicData
     * @param aliases
     * @return
     */
    @RequestMapping(value = "/student-assessment", method = RequestMethod.PATCH)
    public @ResponseBody String editStudentAssessment(@Secure Login login,
                                                      @PathVariable("courseRoundId") Long courseRoundId,
                                                      BasicData basicData,
                                                      @RequestParam(value = "diseases", required = false) List<String> aliases,
                                                      PostureJoint postureJoint) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            List<Disease> diseases = new ArrayList<>();
            if(aliases != null && aliases.size() > 0) {
                for(String alias : aliases) {
                    diseases.add(Disease.aliasOf(alias));
                }
            }
            
            if(courseRound != null && courseRound.getCoach() == coach) {
                basicInformationService.editStudentAssessment(courseRound, basicData, diseases, postureJoint);
            }
            
            result.success().message("编辑基础数据成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#editBasicData() error", e);
            result.fail().message("编辑基础数据失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param scheduleId
     * @return
     */
    @RequestMapping(value = "/basic-data", method = RequestMethod.GET)
    public ModelAndView BasicData(@Secure Login login,
                                  @PathVariable("courseRoundId") Long courseRoundId,
                                  @RequestParam(value="scheduleId", required = false) Long scheduleId,
                                  @RequestParam(value="back", required = false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/basic-data");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && courseRound.getCoach() == coach) {
            BasicData basicData = basicInformationService.loadBasicData(courseRound);
            
            PostureJoint postureJoint = basicInformationService.loadPostureJoint(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("basicData", basicData);
            modelAndView.addObject("postureJoint", postureJoint);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param BasicData
     * @param aliases
     * @return
     */
    @RequestMapping(value = "/basic-data", method = RequestMethod.PATCH)
    public @ResponseBody String editBasicData(@Secure Login login,
                                              @PathVariable("courseRoundId") Long courseRoundId,
                                              BasicData BasicData,
                                              @RequestParam(value = "diseases", required = false) List<String> aliases) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            List<Disease> diseases = new ArrayList<>();
            if(aliases != null && aliases.size() > 0) {
                for(String alias : aliases) {
                    diseases.add(Disease.aliasOf(alias));
                }
            }
            
            if(courseRound != null && courseRound.getCoach() == coach) {
                basicInformationService.editBasicData(courseRound, BasicData, diseases);
            }
            
            result.success().message("编辑基础数据成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#editBasicData() error", e);
            result.fail().message("编辑基础数据失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/habit", method = RequestMethod.GET)
    public ModelAndView habit(@Secure Login login,
                              @PathVariable("courseRoundId") Long courseRoundId,
                              @RequestParam(value="scheduleId", required = false) Long scheduleId,
                              @RequestParam(value="back", required = false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/habit");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && courseRound.getCoach() == coach) {
            StudentHabit habit = basicInformationService.loadStudentHabit(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("habit", habit);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param habit
     * @return
     */
    @RequestMapping(value = "/habit", method = RequestMethod.PATCH)
    public @ResponseBody String editHabit(@Secure Login login,
                                          @PathVariable("courseRoundId") Long courseRoundId,
                                          StudentHabit habit) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && courseRound.getCoach() == coach) {
                basicInformationService.editStudentHabit(courseRound, habit);
            }
            
            result.success().message("编辑学员习惯成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#editHabit() error", e);
            result.fail().message("编辑学员习惯失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/posture-joint", method = RequestMethod.GET)
    public ModelAndView postureJoint(@Secure Login login,
                                @PathVariable("courseRoundId") Long courseRoundId,
                                @RequestParam(value="scheduleId", required = false) Long scheduleId,
                                @RequestParam(value="back", required = false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/posture-joint");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && courseRound.getCoach() == coach) {
            PostureJoint postureJoint = basicInformationService.loadPostureJoint(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            modelAndView.addObject("postureJoint", postureJoint);
            modelAndView.addObject("scheduleId", scheduleId);
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param postureJoint
     * @return
     */
    @RequestMapping(value = "/posture-joint", method = RequestMethod.PATCH)
    public @ResponseBody String editPostureJoint(@Secure Login login,
                                                 @PathVariable("courseRoundId") Long courseRoundId,
                                                 PostureJoint postureJoint) {
         Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && courseRound.getCoach() == coach) {
                basicInformationService.editPostureJoint(courseRound, postureJoint);
            }
            
            result.success().message("编辑体态/关节成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#editPostureJoint() error", e);
            result.fail().message("编辑体态/关节失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/joint-flexibility", method = RequestMethod.GET)
    public ModelAndView jointFlexibility(@Secure Login login,
                                @PathVariable("courseRoundId") Long courseRoundId,
                                @RequestParam(value="scheduleId", required = false) Long scheduleId,
                                @RequestParam(value="back", required = false) String back) {
        ModelAndView modelAndView = new ModelAndView("courseware/evaluation/joint-flexibility");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null && courseRound.getCoach() == coach) {
            PostureJoint postureJoint = basicInformationService.loadPostureJoint(courseRound);
            
            modelAndView.addObject("courseRoundId", courseRoundId);
            if(postureJoint != null) {
            	modelAndView.addObject("postureSummary", postureJoint.getPostureSummary());
                modelAndView.addObject("jointSummary", postureJoint.getJointSummary());
                modelAndView.addObject("summary", postureJoint.getSummary());
                modelAndView.addObject("scheduleId", scheduleId);
            }
        }
        
        modelAndView.addObject("back", back);
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/joint-flexibility", method = RequestMethod.PATCH)
    public @ResponseBody String editJointFlexibility(@Secure Login login,
                                                     @PathVariable("courseRoundId") Long courseRoundId,
                                                     @RequestParam(value = "postureSummary", required = false) String postureSummary,
                                                     @RequestParam(value = "jointSummary", required = false) String jointSummary,
                                                     @RequestParam(value = "summary", required = false) String summary) {
        Result result = new Result();
        
        try {
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
            
            if(courseRound != null && courseRound.getCoach() == coach) {
                basicInformationService.editJointFlexibility(courseRound, postureSummary, jointSummary, summary);
            }
            
            result.success().message("编辑关节灵活性评估成功");
        } catch (Exception e) {
            logger.error("BasicInformationController#editJointFlexibility() error", e);
            result.fail().message("编辑关节灵活性评估失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
